<template>
  <div class="login">
    <div class="logo">
      <img width="300px" src="~images/hx-logo.png" alt=""/>
      <span></span>
    </div>
    <div class="header">
    </div>
    <div class="content clear">
      <div class="info">
        <div class="title">{{ $t('login.UserLogin') }}</div>
        <transition name="fade">
          <div class="tip" v-if="tipState">{{ errorInfo }}</div>
        </transition>
        <ul>
          <li>
            <span class="name"><Icon type="md-person"/>{{ $t('login.userName') }}</span>
            <div class="inputWrapper">
              <input type="text" :placeholder="$t('login.plsenterauser')" v-model="username" autocomplete='off'/>
            </div>
          </li>
          <li>
            <span class="name"><Icon type="md-key"/>{{ $t('login.password') }}</span>
            <div class="inputWrapper">
              <input type="password" :placeholder="$t('login.plsenterapass')" v-model="password" autocomplete='off'/>
            </div>
          </li>
           <li>
              <span class="name"><Icon type="md-information-circle" />{{ $t('login.验证码') }}</span>
              <div class="inputWrapper">
                  <input type="number" :placeholder="$t('请输入') + $t('login.验证码')" v-model="code" maxlength="4" autocomplete='off' />
              </div>
              <div class="verificationCode" @click="generateCode">
                <img @click="getCaptchaImage" :src="captchaImage">
              </div>
          </li>
          <div class="laug">
            <!-- <Row>
              <Col span='12' align="center">
                <div class="laugitem" :class="langName=='简体中文'?'active':''" @click="changeLang(1)">
                  <img width="20px" src="~images/common/china.png" alt=""/>
                  简体中文
                </div>
              </Col>
              <Col span='12' align="center">
                <div class="laugitem" :class="langName=='English'?'active':''" @click="changeLang(2)">
                  <img width="20px" src="~images/common/english.png" alt=""/>
                  English
                </div>
              </Col>
            </Row> -->
          </div>
        </ul>
        <Button class="loginBtn" @click="loginMethod" v-on:keyup.enter="test" :loading="loading">
          {{ $t('login.login') }}
        </Button>
        <!--                <div class="bottom clear">-->
        <!--                    <span class="rememberPassword" :class="{'selected': isRemember}" @click="rememberPassword">-->
        <!--                        <Icon type="md-checkbox-outline"/>-->
        <!--                        {{$t('login.RebPassword')}}</span>-->
        <!--<span class="forgetPassword"><router-link to="forgetPassword">忘记密码</router-link></span>-->
        <!--                </div>-->
      </div>
    </div>
  </div>

</template>

<script>
import '@/assets/cookie/js-cookie.js';
import store from '@/store/store';
import { TOKEN } from '@/store/types';
import * as jsBase64 from 'js-base64';
import Swiper from 'swiper';
import 'swiper/dist/css/swiper.min.css';


import {
  setCheck,
  setEnterName,
  setToken,
  setUserName,
  setUserNameId
} from '@/util/auth';

const isTong = process.env.NODE_ENV === 'tong';
let ksiot = '';
if (isTong) {
  ksiot = ''
}
export default {
  name: 'login',
  data() {
    return {
      bgHeight: document.documentElement.clientHeight - 80,
      captchaImage: '',
      uuid: '',
      isRemember: true,
      username: '',
      password: '',
      code:'',
      inputCode: '',
      errorInfo: '',
      tipState: false,
      loading: false,
      langName: '',
    }
  },
  created() {
    this.getIcon();
    document.onkeydown = (event) => {
      var key = event.keyCode;
      if (key === 13) {
        this.loginMethod()
      }
    }
    // if(this.$cookies.get('zyKeSenUserName')){
    //     this.username = jsBase64.Base64.decode(this.$cookies.get('zyKeSenUserName'))
    // }
    // if(this.$cookies.get('zyKeSenPassword')){
    //     this.password = jsBase64.Base64.decode(this.$cookies.get('zyKeSenPassword'))
    // }
    if (window.localStorage.getItem('language') == 'en_US') {
      this.langName = 'English'
    } else if (window.localStorage.getItem('language') == 'zh_CN') {
      this.langName = '简体中文'
    }
  },
  mounted() {
    this.getCaptchaImage();
    // this.generateCode();
    // this.carousel();
  },
  methods: {
    changeLang(item) {
      if (item === 1) {
        window.localStorage.setItem('language', 'zh_CN')
        this.langName = '简体中文'
      } else if (item === 2) {
        window.localStorage.setItem('language', 'en_US')
        this.langName = 'English'
      } else {
        window.localStorage.setItem('language', 'zh_CN')
        this.langName = '简体中文'
      }
      window.location.reload()
    },
    getCaptchaImage() {
      this.axios({
        method: 'get',
        url: "/basic/captchaImage",
        params: {}
      }).then(res => {

        if(res && res.code === 200){
          this.captchaImage = 'data:image/png;base64,' + res.data.img;
          this.uuid = res.data.uuid;
        }
      })
    },
    getIcon() {
      window.localStorage.removeItem('app_download_url_waiwang')
      window.localStorage.removeItem('app_qrname_waiwang')
      window.localStorage.removeItem('app_download_url_neiwang')
      window.localStorage.removeItem('app_qrname_neiwang')
      this.axios({
        method: 'get',
        url: "/basic/sys/getSysConfig",
        params: {}
      }).then(res => {
        if (res.code === 200) {
          if (res.data) {
            for (let item of res.data) {
              if (item.configCode == "app_download_url_waiwang") {
                window.localStorage.setItem('app_qrname_waiwang', item.configName);
              }

              if (item.configCode == "app_download_url_neiwang") {
                window.localStorage.setItem('app_qrname_neiwang', item.configName);
              }

              window.localStorage.setItem(item.configCode, item.configVal);
            }
          }
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      });
    },
    rememberPassword() {
      this.isRemember = !this.isRemember
    },
    loginMethod() {
      // this.$router.push({path: decodeURIComponent(this.$route.query.redirect)});
      // return
      if (!this.username) {
        this.errorInfo = this.$t('login.plsenterauser')
        this.tipState = true;
        return false;
      }
      if (!this.password) {
        this.errorInfo = this.$t('login.plsenterapass')
        this.tipState = true;
        return false;
      }

      if(!this.code){
          this.errorInfo = '请输入验证码';
          this.tipState = true;
          return false;
      }

      let params = JSON.stringify({
        'username': this.username,
        'password': this.password,
        'uuid': this.uuid,
        'code': this.code
      });
      this.loading = true;
      this.axios({
        method: 'post',
        url: "/basic/token/login",
        headers: {
          token: ""
        },
        data: params
      }).then(response => {
        if (response.code === 200) {
          if (this.isRemember) {
            let Base64 = jsBase64.Base64;
            let userName = Base64.encode(this.username);
            let password = Base64.encode(this.password);
            this.$cookies.set('zyKeSenUserName', userName, {expires: 30});
            this.$cookies.set('zyKeSenPassword', password, {expires: 30});
          } else {
            this.$cookies.remove('zyKeSenUserName');
            this.$cookies.remove('zyKeSenPassword');
          }
          window.localStorage.setItem('ziyunFactoryPortalToken', response.data.token);
          window.localStorage.setItem('ziyunFactoryPortalName', response.data.realname);
          window.localStorage.setItem('ziyunFactoryUserId', response.data.userId);
          window.localStorage.setItem('ziyunFactoryUserRoleId', response.data.roleId);
          window.localStorage.setItem('ziyunFactoryUserRoleName', response.data.roleName);
          window.localStorage.setItem('ziyunFactoryUserPhone', response.data.phone);
          localStorage.setItem('KaPortalJumpMenu', '')
          store.commit(TOKEN, response.data.token);
          this.tipState = false;
          this.initSubInfo(response.data.lgUser)
        } else {
          this.errorInfo = response.msg;
          this.tipState = true;
          this.loading = false;
          this.getCaptchaImage();
        }
      })
    },
    initSubInfo(data){
       if(data){
          const token = data.token
          const name = data.name
          const userId = data.id
          const tsEnterId = data.tsEnterId;
          const identityAuthentication = data.id
          const enterName = data.enterName || '**'
          sessionStorage.setItem('tsEnterId', tsEnterId)
          localStorage.setItem('identityAuthentication', identityAuthentication);
          localStorage.setItem('enterShortName',data.enterShortName)
          localStorage.setItem('isSuperAdmin', JSON.stringify(data.isSuperAdmin === '1'?['admin']:['user']))
          let check = true; // 保持登录
          setToken(token, check)
          setUserName(name, check)
          setEnterName(enterName, check)
          setUserNameId(userId, check)
          setCheck(check)
          this.Jump();
        }
    },
    Jump() {
      if (this.$route.query.redirect) {
        this.$router.push({path: decodeURIComponent(this.$route.query.redirect)});
      } else {
        this.axios({
          method: 'get',
          url: '/basic/menu/findMenuByToken',
          params: {
            menuType: 1,
          },
        }).then((res) => {
          if (res.code === 200) {
            if (res.data && res.data.length > 0) {
              if (res.data[0].url !== "###") {
                window.location.href = ksiot + res.data[0].url;
              } else {
                if (res.data[0].children && res.data[0].children.length > 0) {
                  if (res.data[0].children[0].url !== "###") {
                    window.location.href = '/productManage/moldinstallationRecord';
                  } else {
                    if (res.data[0].children[0].children && res.data[0].children[0].children.length > 0) {
                      // window.location.href = ksiot + res.data[0].children[0].children[0].url;
                    }
                  }
                }
              }
              // this.$Message.success(this.$t('login.loginSucc'));
            } else {
              this.$Message.warning(({content: this.$t('login.loginErr'), duration: 6, closable: true}));
              this.loading = false;
              return false
            }
          }
        })
      }

    },
    carousel() {
      let mySwiper = new Swiper('.swiper-container', {
        loop: true,
        speed: 1000,
        autoplay: {
          delay: 3000,
          disableOnInteraction: false,
        },
        pagination: {
          el: '.swiper-pagination',
          clickable: true,
        },
      });
    },
    generateCode() {
      this.generate();
      let codeArr = ['2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
      this.code = [];
      for (let i = 0; i < 4; i++) {
        let num = Math.floor(Math.random() * 53);
        this.code.push(codeArr[num]);
      }
    },
    generate() {
      this.colors = [];
      for (let i = 0; i < 4; i++) {
        let obj = {};
        let r = Math.floor(Math.random() * 250);
        let g = Math.floor(Math.random() * 250);
        let b = Math.floor(Math.random() * 250);
        if (Math.random() * 10 > 5) {
          obj.rote = 'rotate(' + parseInt(Math.random() * 30) + 'deg)';
        } else {
          obj.rote = 'rotate(' + parseInt(Math.random() * 30) * (-1) + 'deg)';
        }
        obj.rgb = "rgb(" + r + ',' + g + ',' + b + ')';
        this.colors.push(obj)
      }
    }
  },
  destroyed() {
    document.onkeydown = null
  }
}
</script>

<style lang="scss">
.login {
  background: #045eaa url(~images/background.png) no-repeat;
  background-size: cover;
  height: 100vh;
  min-height: 760px;
  position: relative;
  min-width: 1240px;

  .logo {
    position: absolute;
    left: 40px;
    top: 40px;
    display: flex;
    align-items: center;

    span {
      font-size: 40px;
      color: rgb(0, 116, 193);
    }
  }

  .header {
    width: 100%;
    height: 80px;
    line-height: 80px;

    img {
      display: inline-block;
      width: 150px;
      height: auto;
      margin-left: 45px;
      vertical-align: middle;
    }

    span {
      display: inline-block;
      vertical-align: middle;
      color: #FBFBFC;
      font-size: 18px;
      margin-left: 48px;
      position: relative;

      &::before {
        display: block;
        content: "";
        height: 30px;
        width: 1px;
        position: absolute;
        left: -20px;
        top: 25px;
        background: rgba(255, 255, 255, 0.2);
      }
    }
  }

  .content {
    width: 1326px;
    margin: 40px auto 0 auto;
    height: 80%;

    .info {
      width: 490px;
      height: 617px;
      float: right;
      background: #fff;
      border-radius: 5px;
      padding: 0 50px;
      position: relative;

      .laug {
        height: 80px;
        padding: 20px 0;

        .laugitem {
          cursor: pointer;
          height: 40px;
          line-height: 40px;
          font-size: 16px;

          img {
            position: relative;
            // top: 4px;
          }
        }

        .active {
          background-color: rgb(244, 247, 252);
        }
      }

      .title {
        margin-top: 45px;
        width: 100%;
        text-align: center;
        color: #555555;
        font-size: 24px;
        margin-bottom: 63px;
      }

      .tip {
        height: 40px;
        border: 1px solid #fb5d77;
        border-radius: 5px;
        background: #ffeef1;
        color: #fb5d77;
        line-height: 40px;
        padding-left: 50px;
        position: absolute;
        width: 340px;
        top: 96px;
        left: 50px;
      }

      ul {
        li {
          height: 80px;
          border-bottom: 1px solid rgba(153, 153, 153, 1);
          color: #777777;
          display: block;
          position: relative;

          .name {
            width: 120px;
            display: block;
            float: left;
            font-size: 14px;
            line-height: 79px;

            i {
              margin-right: 20px;
            }
          }

          .inputWrapper {
            margin-left: 100px;

            input {
              width: 66%;
              height: 79px;
              line-height: 79px;
              border: none;
            }
          }

          .verificationCode {
            position: absolute;
            right: 0;
            top: 10px;
            line-height: 56px;
            cursor: pointer;

            img {
              display: inline-block;
            }
          }
        }
      }

      .loginBtn {
        width: 390px;
        height: 60px;
        border-radius: 30px;
        background: rgba(44, 177, 251, 1);
        font-size: 20px;
        color: #fff;
        line-height: 60px;
        text-align: center;
        // margin:50px auto 0 auto;
        display: block;
        cursor: pointer;
        border: none;
      }

      .bottom {
        margin-top: 20px;

        .forgetPassword {
          float: right;
          color: #777;
          font-size: 14px;
        }

        .rememberPassword {
          float: left;
          color: #777;
          font-size: 14px;
          cursor: pointer;

          i {
            margin-right: 10px;
          }
        }

        .selected {
          i {
            color: #fff;
            background: #ffba00;
          }
        }
      }

      i {
        font-size: 16px;
      }

    }
  }

  .loginCopyRight {
    position: absolute;
    bottom: 0;
    width: 100%;
    background: rgba(255, 255, 255, 0.05);
    line-height: 40px;
    height: 40px;
    text-align: center;
    color: #9e9e9e;
    font-size: 12px;
  }

  .fade-enter-active, .fade-leave-active {
    transition: opacity .5s;
  }

  .fade-enter, .fade-leave-to {
    opacity: 0;
  }
}
</style>
